<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @author CHUN Dany <chundany@gmail.com>
 */
class Authentication extends My_Controller
{
  private $redirect = 'index/index/view';

  /**
   * Check user logged in
   *
   * if(!$this->session->userdata('isSiteLogin')){
   *   redirect('login');
   *   exit();
   * }
   * 
   * @return boolean [description]
   */
  public function is_logged_in()
  {
    redirectUnless($this->session->userdata('isSiteLogin'), 'login');
  }
  
  public function login()
  {
    redirectIf($this->session->userdata('isSiteLogin'), $this->redirect);

    $this->load->model('mod_authentication');
  
    if($this->input->post())
    {
      $this->form_validation->set_rules('username','Username', 'trim|xss_clean|required|max_length[45]');
      $this->form_validation->set_rules('password','Password', 'trim|xss_clean|required|max_length[45]');
      
      if($this->form_validation->run() === TRUE)
      {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $remember = $this->input->post('remember');

        if($this->mod_authentication->login($username, mkpwd($password)))
        {
          if($remember)
          {
            $cookie_user = array(
              'name'   => 'dn_site_u',
              'value'  => $username,
              'expire' => '2592000'
            );
            
            $cookie_pass = array(
              'name'   => 'dn_site_p',
              'value'  => $password,
              'expire' => '2592000'
            );
            $this->input->set_cookie($cookie_user);
            $this->input->set_cookie($cookie_pass);
          }
          else
          {
            delete_cookie('dn_site_u');
            delete_cookie('dn_site_p');
          }

          redirect($this->redirect);
          exit();
        }
        $this->session->set_userdata('ms','<div class="red">Invalid account!</div>');
      }
      else
      {
        $this->session->set_userdata('ms', '<div class="red">Invalid information!</div>');  
      }
    }

    $this->title = 'Login';
  }
    
  public function logout()
  {
    $this->session->sess_destroy();
    redirect('login');
  }
  
  public function forgot_password()
  {
    // Page not found if attemp from url
    forward404Unless($this->input->post());

    // Validate email format
    $this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|valid_email');
    $this->form_validation->set_error_delimiters('', '');

    if($this->form_validation->run() === TRUE)
    {
      // Load model
      $this->load->model('mod_reset_password', 'mod_password');
      // Get email from text box
      $email = $this->input->post('email');
      
      if($this->mod_password->isEmailExists($email))
      {
        // Generate a uniq key
        $token = md5(uniqid(mt_rand(), TRUE));
        // Config send mail
        $from = SYSTEM_EMAIL;
        $to = $email;
        $cc = '';
        $subject = 'Reset your Password (Online Library Management System)';
        $message = '<p>This email has been sent as a request to reset our password</p>';
        $message .= '<p><a href="'.site_url('rspwd/'.$token).'">Click here </a>if you want to reset your password, if not, then ignore</p>';
        
        // Add reset token then do send mail process      
        if($this->mod_password->addTempReset($email, $token) && send_mail($from, $to, $cc, $subject, $message))
        {
          // Succeffull message
          $data['ms'] = 'Please check your email to reset your password!';
          $data['type'] = 'success';
        }
        else
        {
          // Error when save fail or send mail fail
          $data['ms'] = 'Unable to send email, Please try again!';
          $data['type'] = 'error';
        }
      }
      else
      {
        // Email does not exits
        $data['ms'] = 'Invailid information!';
        $data['type'] = 'error';
      }
    }
    else
    {
      // Invalid form validation
      $data['ms'] = form_error('email');
      $data['type'] = 'error';
    }
    
    $this->setLayout(null);
    $this->output->set_content_type('application/json')->set_output(json_encode($data));
  }
  
  public function reset_password()
  {
    // Load model
    $this->load->model('mod_reset_password', 'mod_password');
    // Check valid token
    $token = $this->uri->segment(2);
    showErrorUnless(($token && $this->mod_password->isExistToken($token)), 'Key was expired, please try again!');
    
    $this->token = $token;        
    $this->title = 'Reset Password';
    $this->layout = 'login';
  }
  
  public function change_password()
  {
    // Load model
    $this->load->model('mod_reset_password', 'mod_password');
    // Check key and post form
    $token = $this->uri->segment(2);
    // Page not found if attemp from url
    forward404Unless($token && $this->mod_password->isExistToken($token) && $this->input->post());

    // Form validation
    $this->form_validation->set_rules('password', 'Password', 'required|trim|xss_clean|min_length[5]');
    $this->form_validation->set_rules('repassword', 'Repeat Password', 'required|trim|xss_clean|matches[password]');
    $this->form_validation->set_error_delimiters('', '');

    if($this->form_validation->run())
    {
      // Retrieve form value
      $password = $this->input->post('password');
      // Get email by token
      $email = $this->mod_password->getEmailReset($token);
      if($email && $password)
      {
        // 
        if($this->mod_password->resetPassword($password, $email, $token))
        {
          // Succeffull message
          $data['ms'] = 'Password reset successfully, please login to your account!';
          $data['type'] = 'success';
        }
        else
        {
          // Error reset password
          $data['ms'] = 'Unable to reset password, Please try again!';
          $data['type'] = 'error';
        }
      }
      else
      {
        // Email does not exits
        $data['ms'] = 'Invailid information!';
        $data['type'] = 'error';
      }
    }
    else
    {
      // Invalid form validation
      $data['ms'] = validation_errors();
      $data['type'] = 'error';
    }
    
    $this->setLayout(null);
    $this->output->set_content_type('application/json')->set_output(json_encode($data));
  }
}
